package yu.zhou.njupt.convertencoding;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;

public class Main {

	public static void main(String[] args) {
		try {
			Properties props = new Properties();
			props.load(Main.class.getClassLoader().getResourceAsStream("config.properties"));

			convertEncoding(
					new File(props.getProperty("sourcePath")).getAbsolutePath(),
					props.getProperty("sourcePath"), 
					props.getProperty("targetPath"), 
					props.getProperty("sourceCharset"), 
					props.getProperty("targetCharset"),
					Integer.valueOf(props.getProperty("bytesPerRead"))
					);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void convertEncoding(
			String sourcePath, String currentPath, String outPath, String sourceCharset, String targetCharset, int bytesPerRead) throws IOException{
		FileInputStream fis;
		FileOutputStream fos;
		String filename;
		String nextCurrentPath; //子目录
		String nextOutPath; //子目录对应的输出目录
		int num; //读取的byte数
		byte[] bytes = new byte[bytesPerRead];

		for (File file : new File(currentPath).listFiles()) {
			filename = file.getName();
			if (file.isDirectory()) {
				nextCurrentPath = file.getAbsolutePath();
				nextOutPath = outPath + nextCurrentPath.replace(sourcePath, "");
				if (!new File(nextOutPath).exists()) {
					new File(nextOutPath).mkdirs();
				}
				
				convertEncoding(
						sourcePath,
						nextCurrentPath,
						nextOutPath,
						sourceCharset, 
						targetCharset, 
						bytesPerRead
						);
			} else {
				fis = new FileInputStream(file);
				fos = new FileOutputStream(new File(outPath + File.separator + filename));
				
				num = fis.read(bytes, 0, bytesPerRead);
				while (num != -1) {
					fos.write(new String(bytes, 0, num, Charset.forName(sourceCharset)).getBytes(targetCharset));
					num = fis.read(bytes, 0, bytesPerRead);
				}

				fis.close();
				fos.close();
			}
		}
	}

}